//
// Created by sgyt on 2020/4/9.
// 自旋锁
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#define MAXLEN 1024
pthread_spinlock_t lock;

char buf[MAXLEN] = "";

void* pthread_read();
void* pthread_write();

int main(int argc,char *argv[])
{
    int res;
    pthread_t pthread1,pthread2;

    //初始化自旋锁
    pthread_spin_init(&lock,PTHREAD_PROCESS_SHARED);

    //创建线程
    res = pthread_create(&pthread1,NULL,pthread_read,NULL);
    if(res != 0)
    {
        perror("pthread_create1 is error\n");
        exit(EXIT_FAILURE);
    }
    res = pthread_create(&pthread2,NULL,pthread_write,NULL);
    if(res != 0)
    {
        perror("pthread_create2 is error\n");
        exit(EXIT_FAILURE);
    }


    //等待线程
    pthread_join(pthread1,NULL);
    pthread_join(pthread2,NULL);

    printf("buf:\n%s\n", buf);

    pthread_spin_destroy(&lock);

    return 0;
}

void *pthread_read()
{
    pthread_spin_lock(&lock);
    int i = 0;
    for(i = 0; i < 5; i++)
    {
        printf("read one\n");
        sleep(1);
    }
    pthread_spin_unlock(&lock);
}


void *pthread_write()
{
    pthread_spin_lock(&lock);
    int i;
    for(i = 0; i < 5; i++)
    {
        printf("write one\n");
        strcat(buf, "hello write data one\n");
        sleep(1);
    }
    pthread_spin_unlock(&lock);
}

